﻿// <copyright file="MaintenanceController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.Maintenance
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Text;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Newtonsoft.Json;
    using PublicData;
    using PublicModelsAndEntities.Models.MainsortRecord;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.BookInfo;
    using XinjeMesProgram.Entities.Maintenance;

    /// <summary>
    /// 查询界面控制器.
    /// </summary>
    [ApiController]
    [Authorize]
    public class MaintenanceController : ControllerBase
    {
#pragma warning disable SA1000 // Keywords should be spaced correctly
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
#pragma warning disable CS8602 // 解引用可能出现空引用。
        // private ResponseModel response = new ResponseModel();
        private readonly ResponseModel response = new();

        /// <summary>
        /// 根据条件获取数据列表.
        /// </summary>
        /// <param name="pageSize">每页记录条数.</param>
        /// /// <param name="currentPage">当前页码.</param>
        /// <param name="baozhuangDate">包装日期.</param>
        /// <param name="fahuoDate">发货日期.</param>
        /// <param name="repairTime">维修完成时间.</param>
        /// <param name="applyTime">收费申请时间.</param>
        /// <param name="chargeCompletionTime">收费完成时间.</param>
        /// <param name="feiyong">收费.</param>
        /// <param name="oN1">导出开关.</param>
        /// <param name="shippingNumber">发货编号.</param>
        /// <param name="oneDimensionalCode">产品序列号（一维码）.</param>
        /// <param name="name">客户名称（实则为购货单位）.</param>
        /// <param name="weixiuDate">维修时间.</param>
        /// <param name="warehousingDate">收货日期.</param>
        /// <param name="trackingNumber">快递单号.</param>
        /// <param name="assignpersonnel">工程师.</param>
        /// <param name="department">部门.</param>
        /// <param name="state">状态.</param>
        /// <param name="productModel">型号.</param>
        /// <param name="customerPhone">电话.</param>
        /// <returns>返回列表数据.</returns>
        /// <returns> .</returns>
        [Route("/api/v1/maintenance/maintenanceQuery")]
        [HttpGet]
        public ResponseModel MainQuery(int pageSize, int currentPage, string? baozhuangDate, string? fahuoDate, string? repairTime, string? applyTime, string? chargeCompletionTime, string? feiyong, int? oN1, string? shippingNumber, string? oneDimensionalCode, string? name, string? weixiuDate, string? warehousingDate, string? trackingNumber, string? assignpersonnel, string? department, string? state, string? productModel, string? customerPhone)
        {
            using (var context = new FactoryMesContext())
            {
                /*var query = from sr in context.MainsortRecord // 分拣表
                            join cost in context.MaintenanceCost on sr.ID equals cost.ID // 收费表
                            join rp in context.RepairProduct on sr.ID equals rp.ProductId // 维修表
                            join d in context.Deliver on sr.ID equals d.ProductId // 发货表*/
                var query = from sr in context.MainsortRecord // 主表
                            join cost in context.MaintenanceCost // 左连接维修成本表
                              on sr.ID equals cost.ID into costGroup
                            from cost in costGroup.DefaultIfEmpty()
                            join rp in context.RepairProduct // 左连接维修产品表
                              on sr.ID equals rp.ProductId into rpGroup
                            from rp in rpGroup.DefaultIfEmpty()
                            join d in context.Deliver // 左连接交付表
                              on sr.ID equals d.ProductId into dGroup
                            from d in dGroup.DefaultIfEmpty()
                            select new MaintenanceQueryModel
                            {
                                Id = sr.ID,
                                WarehousingDate = sr.WarehousingDate,                   // 收货时间
                                Delivery_nameIn = sr.Delivery_NameIn,                   // 收货快递名称
                                Delivery_numberIn = sr.Delivery_NumberIn,               // 收货快递单号
                                Name = sr.Name,                                         // 客户名称（实则为购货单位）
                                Contact_information = sr.Contact_Information,           // 客户联系方式
                                Consignee = sr.Consignee,
                                Receiving_contact = sr.Receiving_Contact,
                                Shipping_address = sr.Shipping_Address,                 // 收货地址
                                One_dimensional_code = sr.One_Dimensional_Code,         // 产品序列号
                                Product_model = sr.Product_Model,                       // 产品型号
                                Product_category = sr.Product_Category,                 // 产品类别
                                Product_classification = sr.Product_Classification,     // 产品分类
                                Product_Name = sr.Product_Name,                         // 产品名称
                                Guarantee = sr.Guarantee,                               // 包内/保外
                                Purchasing_unit = sr.Purchasing_Unit,                   // 购货单位
                                Salesman = sr.Salesman,                                 // 业务员
                                Delivery_time = sr.Delivery_Time,                       // 首次出库时间
                                First_iaddress = sr.First_Address,                      // 首次出库地址信息
                                ApplyRepairTime = rp.MaintenanceEntryTime == null ? string.Empty : rp.MaintenanceEntryTime.Value.ToString("yyyy-MM-dd") ?? string.Empty,
                                RepairTime = rp.RepairTime,                             // 维修完成时间2
                                State = sr.State,                                       // 状态
                                Datex = d.DeliveryTime.ToString(),                      // 发货时间
                                Data = rp.Data,                                         // 维修记录
                                ShippingNumber = rp.ShippingNumber,                     // 发货编号
                                AssignPersonnel = context.MesUserRole.FirstOrDefault(x => x.ID == sr.AssignPersonnelUserId).UserName ?? string.Empty, // 工程师
                                RepairOr = rp.RepairOr,                                 // 是否维修
                                Receivable = cost.Receivable,                           // 应收的钱
                                NetReceipts = cost.NetReceipts,                         // 实际收的钱
                                Delivery_nameOut = d.NameOut,                           // 发货快递名称
                                Delivery_numberOut = d.NumberOut,                       // 发货快递单号
                                PackagingTime = d.PackagingTime,                        // 包装时间
                                Product_handle = rp.ProductHandle,
                                ChargeCompletionTime = cost.UnlockTime.Value.ToString("yyyy/MM/dd"),      // 收费解锁时间
                                ApplyTime = cost.ApplyTime.Value.ToString("yyyy/MM/dd"), // 收费申请时间
                                SortingSpecialist = sr.SortingSpecialist, // 分拣专员
                                Notes = rp.Notes,
                            };

                List<MaintenanceQueryModel> result = query.ToList();

                // 根据客户联系方式进行模糊查询
                if (!string.IsNullOrEmpty(customerPhone))
                {
                    result = result.Where(x => x.Contact_information.Contains(customerPhone)).ToList();
                }

                // 根据产品类型进行模糊查询
                if (!string.IsNullOrEmpty(productModel))
                {
                    result = result.Where(x => x.Product_model.Contains(productModel)).ToList();
                }

                // 根据产品一维码进行模糊查询
                if (!string.IsNullOrEmpty(oneDimensionalCode))
                {
                    // result = result.Where(x => x.one_dimensional_code.Contains(oneDimensionalCode)).ToList();
                    result = result.Where(x => x.One_dimensional_code.IndexOf(oneDimensionalCode, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
                }

                // 根据客户名称进行模糊查询
                if (!string.IsNullOrEmpty(name))
                {
                    result = result.Where(x => x.Name.Contains(name)).ToList();
                }

                // 根据发货编号进行模糊查询
                if (!string.IsNullOrEmpty(shippingNumber))
                {
                    result = result.Where(x => x.ShippingNumber != null && x.ShippingNumber.Contains(shippingNumber)).ToList();
                }

                // 判断收费情况
                if (!string.IsNullOrEmpty(feiyong))
                {
                    // result = result.Where(x => x.shippingNumber != null && x.netReceipts.Contains(feiyong)).ToList();
                    if (feiyong == "收费")
                    {
                        result = result.Where(x => x.Receivable != null || x.State == "4").ToList();
                    }
                    else if (feiyong == "收费完成")
                    {
                        result = result.Where(x => x.NetReceipts != "0.00" && x.NetReceipts != null && x.State != "4").ToList();
                    }
                    else if (feiyong == "未收费完成")
                    {
                        result = result.Where(x => (x.NetReceipts == "0.00" || x.NetReceipts == null) && x.State == "4").ToList();
                    }
                }

                // 按照日期筛选  这里是包装日期(现在改为费用申请时间)
                if (!string.IsNullOrEmpty(baozhuangDate))
                {
                    string[] wareho = baozhuangDate.Split(',');
                    result = result.Where(x => x.ApplyTime != null && DateTime.Compare(DateTime.Parse(x.ApplyTime), DateTime.Parse(wareho[0])) >= 0).ToList();
                    result = result.Where(x => x.ApplyTime != null && DateTime.Compare(DateTime.Parse(x.ApplyTime), DateTime.Parse(wareho[1])) <= 0).ToList();
                }

                // 按照日期筛选  这里是发货装日期
                if (!string.IsNullOrEmpty(fahuoDate))
                {
                    string[] wareho = fahuoDate.Split(',');
                    result = result.Where(x => x.Datex != null && DateTime.Compare(DateTime.Parse(x.Datex[..10]), DateTime.Parse(wareho[0])) >= 0).ToList();
                    result = result.Where(x => x.Datex != null && DateTime.Compare(DateTime.Parse(x.Datex[..10]), DateTime.Parse(wareho[1])) <= 0).ToList();
                }

                // 根据收货快递单号进行模糊查询
                if (!string.IsNullOrEmpty(trackingNumber))
                {
                    result = result.Where(x => x.Delivery_numberIn.Contains(trackingNumber)).ToList();
                }

                // 按照维修日期筛选
                if (!string.IsNullOrEmpty(weixiuDate))
                {
                    string[] weixiu = weixiuDate.Split(',');
                    string[] weixiu1 = weixiu[0].Split('-');
                    string[] weixiu2 = weixiu[1].Split('-');
                    DateTime startDate = new(int.Parse(weixiu1[0]), int.Parse(weixiu1[1]), int.Parse(weixiu1[2]));
                    DateTime endDate = new(int.Parse(weixiu2[0]), int.Parse(weixiu2[1]), int.Parse(weixiu2[2]));

                    // 计算日期范围内的总天数，并创建对应大小的数组
                    int totalDays = (endDate - startDate).Days + 1;
                    DateTime[] dates = new DateTime[totalDays];

                    // 使用循环将每个日期添加到数组中
                    var result2 = result;
                    for (int i = 0; i < totalDays; i++)
                    {
                        dates[i] = startDate.AddDays(i);
                        Console.WriteLine(dates[i].ToString("yyyy-M-d"));
                        var result1 = result.Where(x => x.Data != null && x.Data.Contains("\"" + dates[i].ToString("yyyy-M-d") + "\"")).ToList();
                        if (i >= 1)
                        {
                            result2 = result2.Concat(result1).Distinct().ToList();
                        }
                        else
                        {
                            result2 = result1;
                        }
                    }

                    result = result2;
                }

                // 按照日期筛选  这里是收费申请时间
                if (!string.IsNullOrEmpty(applyTime))
                {
                    string[] rpptime = applyTime.Split(',');
                    result = result.Where(x => x.ApplyTime != null && DateTime.Compare(DateTime.Parse(x.ApplyTime[..10]), DateTime.Parse(rpptime[0])) >= 0).ToList();
                    result = result.Where(x => x.ApplyTime != null && DateTime.Compare(DateTime.Parse(x.ApplyTime[..10]), DateTime.Parse(rpptime[1])) <= 0).ToList();
                }

                // 按照日期筛选  这里是收费完成时间
                if (!string.IsNullOrEmpty(chargeCompletionTime))
                {
                    string[] rpptime = chargeCompletionTime.Split(',');
                    result = result.Where(x => x.ChargeCompletionTime != null && DateTime.Compare(DateTime.Parse(x.ChargeCompletionTime[..10]), DateTime.Parse(rpptime[0])) >= 0).ToList();
                    result = result.Where(x => x.ChargeCompletionTime != null && DateTime.Compare(DateTime.Parse(x.ChargeCompletionTime[..10]), DateTime.Parse(rpptime[1])) <= 0).ToList();
                }

                // 按照日期筛选  这里是维修完成时间
                if (!string.IsNullOrEmpty(repairTime))
                {
                    string[] rpptime = repairTime.Split(',');
                    result = result.Where(x => x.RepairTime != null && DateTime.Compare(DateTime.Parse(x.RepairTime[..10]), DateTime.Parse(rpptime[0])) >= 0).ToList();
                    result = result.Where(x => x.RepairTime != null && DateTime.Compare(DateTime.Parse(x.RepairTime[..10]), DateTime.Parse(rpptime[1])) <= 0).ToList();
                }

                // 按照日期筛选  这里是入库日期
                if (!string.IsNullOrEmpty(warehousingDate))
                {
                    string[] wareho = warehousingDate.Split(',');
                    result = result.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[0])) >= 0).ToList();
                    result = result.Where(x => DateTime.Compare(DateTime.Parse(x.WarehousingDate[..10]), DateTime.Parse(wareho[1])) <= 0).ToList();
                }

                // 根据部门进行模糊查询
                if (!string.IsNullOrEmpty(department))
                {
                    Console.WriteLine(result);
                    result = result.Where(x => x.Product_category != null && x.Product_category.Contains(department)).ToList();
                }

                // 根据分配人员进行模糊查询
                if (!string.IsNullOrEmpty(assignpersonnel))
                {
                    Console.WriteLine(result);
                    result = result.Where(x => x.AssignPersonnel.Contains(assignpersonnel)).ToList();
                }

                // 根据产品状态进行模糊查询
                if (!string.IsNullOrEmpty(state))
                {
                    result = result.Where(x => x.State.Contains(state)).ToList();
                }

                result = result.OrderByDescending(x => x.WarehousingDate).ToList(); // 收货时间按降序排列
                this.response.SetData(result.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(), result.Count);

                // 含维修记录导出
                if (oN1 == 1)
                {
                    StringBuilder csvContent = new();
                    csvContent.AppendLine("收货日期,维修时间,收费申请时间,收费完成解锁时间,维修完成时间,产品处理(是否收费),是否超期,发货编号,客户名称,产品编码,产品规格型号,产品分类,产品组类别,保内/保外" +
                        ",状态,工程师名称,产品细分,回访记录,类型(伺服),产品内码,产品日期,二维码/外加工厂家,问题归类,故障类型,故障细分,故障原因(电机),原因细分(电机)," +
                        "编码器编码(电机),器件规格,品牌,位号,客户反应现象,维修检测现象,故障原因分析,故障处理,PCB丝印,测台标志位(驱动),报警记录,软件版本" +
                        ",运行时间h,运行时间min,备注,X电阻(数字),Y电阻(数字),绝缘电阻(数字),电容(数字),图片链接,购货单位,业务员");  // 核对导出表 表头

                    foreach (var book in result)
                    {
                        if (book.Data != null)
                        {
                            RepairCatalogModel catalogModel = JsonConvert.DeserializeObject<RepairCatalogModel>(book.Data);
                            Maintenancerecords records = new();
                            if (catalogModel.picAddress != null)
                            {
                                for (int i = 0; i < catalogModel.picAddress.Count; i++)
                                {
                                    records.picAddress1 = records.picAddress1 + catalogModel.picAddress[i] + ",";
                                }
                            }

                            if (catalogModel.list != null)
                            {
                                foreach (var book1 in catalogModel.list)
                                {
                                    if (book1.key == "repairTime")
                                    {
                                        records.repairTime = book1.value;
                                    }

                                    if (book1.key == "back_record")
                                    {
                                        records.back_record = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "type")
                                    {
                                        records.type = book1.value;
                                    }

                                    if (book1.key == "product_code")
                                    {
                                        records.product_code = book1.value;
                                    }

                                    if (book1.key == "product_date")
                                    {
                                        records.product_date = book1.value;
                                    }

                                    if (book1.key == "2D_factory" || book1.key == "2-Dbarcode")
                                    {
                                        // records.D2_factory = book1.value;
                                        records.D2_factory = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "question_classify")
                                    {
                                        records.question_classify = book1.value;
                                    }

                                    if (book1.key == "error_type")
                                    {
                                        records.error_type = book1.value;
                                    }

                                    if (book1.key == "error_detail" || book1.key == "kind")
                                    {
                                        records.error_detail = book1.value;
                                    }

                                    if (book1.key == "reason_detail")
                                    {
                                        records.reason_detail = book1.value;
                                    }

                                    if (book1.key == "error_reason")
                                    {
                                        records.error_reason = book1.value;
                                    }

                                    if (book1.key == "encrypt")
                                    {
                                        records.encrypt = book1.value;
                                    }

                                    if (book1.key == "product_size")
                                    {
                                        records.product_size = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "brand")
                                    {
                                        records.brand = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "position")
                                    {
                                        records.position = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "guarantee")
                                    {
                                        records.guarantee = book1.value;
                                    }

                                    if (book1.key == "custom_reply_phenomenon")
                                    {
                                        records.custom_reply_phenomenon = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "repair_phenomenon")
                                    {
                                        records.repair_phenomenon = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "reason_analysis")
                                    {
                                        records.reason_analysis = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "alarm_record")
                                    {
                                        records.alarm_record = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "error_deal")
                                    {
                                        records.error_deal = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "PCBsiyin")
                                    {
                                        records.PCBsiyin = book1.value;
                                    }

                                    if (book1.key == "P172")
                                    {
                                        records.P172 = book1.value;
                                    }

                                    if (book1.key == "software_edition")
                                    {
                                        records.software_edition = book1.value.Replace(",", "，");
                                    }

                                    if (book1.key == "run_time_h")
                                    {
                                        records.run_time_h = book1.value;
                                    }

                                    if (book1.key == "run_time_min")
                                    {
                                        records.run_time_min = book1.value;
                                    }

                                    if (book1.key == "remark")
                                    {
                                        records.remark = book1.value;
                                    }

                                    if (book1.key == "Xdata")
                                    {
                                        records.Xdata = book1.value;
                                    }

                                    if (book1.key == "Ydata")
                                    {
                                        records.Ydata = book1.value;
                                    }

                                    if (book1.key == "insulation")
                                    {
                                        records.insulation = book1.value;
                                    }

                                    if (book1.key == "capacitance")
                                    {
                                        records.capacitance = book1.value;
                                    }
                                }
                            }

                            RepairProductModel repair = new();
                            string csvLine = string.Format(
                                "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29}," +
                                "{30},{31},{32},{33},{34},{35},{36},{37},{38},{39},{40},{41},{42},{43},{44},{45},{46},{47},{48}",
                                book.WarehousingDate[..10],         // 收货日期
                                records.repairTime,                 // 维修时间
                                book.ApplyTime, // 收费申请时间
                                book.ChargeCompletionTime,          // 收费完成解锁时间
                                book.RepairTime != null ? DateTime.ParseExact(book.RepairTime, "yyyy-M-d HH:mm:ss", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd") : string.Empty, // 维修完成时间
                                book.Product_handle,                // 产品处理(是否收费)
                                book.Datex == null ? (DateTime.ParseExact(DateTime.Now.ToString("yyyy/MM/dd"), "yyyy/MM/dd", CultureInfo.InvariantCulture) - DateTime.ParseExact(book.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days - 1 <= 7 ? "正常" : "超期" : (DateTime.Parse(book.Datex[..10]) - DateTime.Parse(book.WarehousingDate[..10])).Days - 1 <= 7 ? "正常" : "超期", // 是否超期
                                book.ShippingNumber,                // 发货编号
                                book.Name,                          // 客户名称
                                book.One_dimensional_code,          // 产品编码
                                book.Product_model,                 // 产品规格型号
                                book.Product_classification,        // 产品分类
                                book.Product_category,              // 产品组类别
                                records.guarantee,                  // 保内/保外
                                book.State == "1" ? "已收货" : book.State == "2" ? "待核对" : book.State == "3" ? "待维修" : book.State == "4" ? "收费中" : book.State == "5" ? "维修中" : book.State == "6" ? "维修完成" : book.State == "7" ? "已包装" : book.State == "8" ? "已发货" : "异常", // 状态
                                book.AssignPersonnel,               // 工程师名称
                                catalogModel.detailchoose,          // 产品细分
                                records.back_record,                // 回访记录
                                records.type,                       // 类型(伺服)
                                records.product_code,               // 产品内码
                                records.product_date,               // 产品日期
                                records.D2_factory,                 // 二维码/外加工厂家
                                records.question_classify,          // 问题归类
                                records.error_type,                 // 故障类型
                                records.error_detail,               // 故障细分
                                records.error_reason,               // 故障原因(电机)
                                records.reason_detail,              // 原因细分(电机)
                                records.encrypt,                    // 编码器编码(电机)
                                records.product_size,               // 器件规格
                                records.brand,                      // 品牌
                                records.position,                   // 位号
                                records.custom_reply_phenomenon,    // 客户反应现象
                                records.repair_phenomenon,          // 维修检测现象
                                records.reason_analysis,            // 故障原因分析
                                records.error_deal,                 // 故障处理
                                records.PCBsiyin,                   // PCB丝印
                                records.P172,                       // 测台标志位(驱动)
                                records.alarm_record,               // 报警记录
                                records.software_edition,           // 软件版本
                                records.run_time_h,                 // 运行时间h
                                records.run_time_min,               // 运行时间min
                                records.remark,                     // 备注
                                records.Xdata,                      // X电阻(数字)
                                records.Ydata,                      // Y电阻(数字)
                                records.insulation,                 // 绝缘电阻(数字)
                                records.capacitance,                // 电容(数字)
                                records.picAddress1 == null ? string.Empty : records.picAddress1.Replace(",", "，"),                // 图片链接
                                book.Purchasing_unit,               // 购货单位
                                book.Salesman);                     // 销售员

                            csvContent.AppendLine(csvLine);
                        }
                        else
                        {
                            string csvLine = string.Format(
                                "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29}," +
                                "{30},{31},{32},{33},{34},{35},{36},{37},{38},{39},{40},{41},{42},{43},{44},{45},{46},{47},{48}",
                                book.WarehousingDate[..10],         // 收货日期
                                string.Empty,                       // 维修时间
                                string.Empty,
                                string.Empty,                       // 收费完成解锁时间
                                string.Empty,                       // 维修完成时间
                                book.Product_handle,                // 产品处理(是否收费)
                                book.Datex == null ? (DateTime.ParseExact(DateTime.Now.ToString("yyyy/MM/dd"), "yyyy/MM/dd", CultureInfo.InvariantCulture) - DateTime.ParseExact(book.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days - 1 <= 7 ? "正常" : "超期" : (DateTime.Parse(book.Datex[..10]) - DateTime.Parse(book.WarehousingDate[..10])).Days - 1 <= 7 ? "正常" : "超期", // 是否超期
                                book.ShippingNumber,                // 发货编号
                                book.Name,                          // 客户名称
                                book.One_dimensional_code,          // 产品编码
                                book.Product_model,                 // 产品规格型号
                                book.Product_classification,        // 产品分类
                                book.Product_category,              // 产品组类别
                                string.Empty,                       // 保内/保外
                                book.State == "1" ? "已收货" : book.State == "2" ? "待核对" : book.State == "3" ? "待维修" : book.State == "4" ? "收费中" : book.State == "5" ? "维修中" : book.State == "6" ? "维修完成" : book.State == "7" ? "已包装" : book.State == "8" ? "已发货" : "异常", // 状态
                                book.AssignPersonnel,               // 工程师名称
                                string.Empty,                       // 产品细分
                                string.Empty,                       // 回访记录
                                string.Empty,                       // 类型(伺服)
                                string.Empty,                       // 产品内码
                                string.Empty,                       // 产品日期
                                string.Empty,                       // 二维码/外加工厂家
                                string.Empty,                       // 问题归类
                                string.Empty,                       // 故障类型
                                string.Empty,                       // 故障细分
                                string.Empty,                       // 原因细分(电机)
                                string.Empty,                       // 故障原因(电机)
                                string.Empty,                       // 编码器编码(电机)
                                string.Empty,                       // 器件规格
                                string.Empty,                       // 品牌
                                string.Empty,                       // 位号
                                string.Empty,                       // 客户反应现象
                                string.Empty,                       // 维修检测现象
                                string.Empty,                       // 故障原因分析
                                string.Empty,                       // 故障处理
                                string.Empty,                       // PCB丝印
                                string.Empty,                       // 测台标志位(驱动)
                                string.Empty,                       // 报警记录
                                string.Empty,                       // 软件版本
                                string.Empty,                       // 运行时间h
                                string.Empty,                       // 运行时间min
                                string.Empty,                       // 备注
                                string.Empty,                       // X电阻(数字)
                                string.Empty,                       // Y电阻(数字)
                                string.Empty,                       // 绝缘电阻(数字)
                                string.Empty,                       // 电容(数字)
                                string.Empty,                       // 图片链接
                                book.Purchasing_unit,               // 购货单位
                                book.Salesman);                     // 销售员
                            csvContent.AppendLine(csvLine);
                        }
                    }

                    string exportFolderPath = "C:\\WebSite\\XinjeMesApi\\wwwroot\\xlsx";
                    string ambin = "查询数据表" + DateTime.Now.ToString("mm-ss") + "(含维修记录).csv";
                    string csvFilePath = Path.Combine(exportFolderPath, ambin);
                    System.IO.File.WriteAllText(csvFilePath, csvContent.ToString(), Encoding.UTF8);
                    string downloadLink = "/xlsx/" + ambin;  // 下载链接
                    this.response.SetSuccess(downloadLink);
                }

                // 不含维修记录的导出
                else if (oN1 == 2)
                {
                    StringBuilder csvContent = new();
                    csvContent.AppendLine("收货日期,分拣专员,是否超期,工程师名称,收货快递名称,收货快递单号,发货编号,发货地址,客户名称,产品编码,产品规格型号,产品组类别,保内/保外" +
                        ",状态,是否维修,应收,实收,维修完成时间,包装时间,收费申请时间,收费完成时间,发货日期,发货快递名称,发货快递号,备注");  // 核对导出表 表头

                    foreach (var book in result)
                    {
                        string csvLine = string.Format(
                            "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24}",
                            book.WarehousingDate != null ? book.WarehousingDate[..10] : string.Empty,     // 收货日期
                            book.SortingSpecialist ?? string.Empty,         // 分拣专员
                            book.Datex == null ? (DateTime.ParseExact(DateTime.Now.ToString("yyyy/MM/dd"), "yyyy/MM/dd", CultureInfo.InvariantCulture) - DateTime.ParseExact(book.WarehousingDate[..10], "yyyy/MM/dd", CultureInfo.InvariantCulture)).Days - 1 <= 7 ? "正常" : "超期" : (DateTime.Parse(book.Datex[..10]) - DateTime.Parse(book.WarehousingDate[..10])).Days - 1 <= 7 ? "正常" : "超期", // 是否超期
                            book.AssignPersonnel ?? string.Empty,           // 工程师名称
                            book.Delivery_nameIn ?? string.Empty,           // 收货快递名称
                            book.Delivery_numberIn ?? string.Empty,         // 收货快递单号
                            book.ShippingNumber ?? string.Empty,            // 发货编号
                            book.Shipping_address != null ? book.Shipping_address.Replace(',', '，') : string.Empty,          // 发货地址
                            book.Name ?? string.Empty,                      // 客户名称
                            book.One_dimensional_code ?? string.Empty,      // 产品编码
                            book.Product_model ?? string.Empty,             // 产品规格型号
                            book.Product_category ?? string.Empty,          // 产品组类别
                            book.Guarantee ?? string.Empty,                 // 保内/保外
                            book.State switch { "1" => "已收货", "2" => "待核对", "3" => "待维修", "4" => "收费中", "5" => "维修中", "6" => "维修完成", "7" => "已包装", "8" => "已发货", _ => "数据异常" },
                            book.RepairOr ?? string.Empty,                  // 是否维修
                            book.Receivable ?? string.Empty,                // 应收
                            book.NetReceipts ?? string.Empty,               // 实收
                            book.RepairTime != null ? DateTime.ParseExact(book.RepairTime, "yyyy-M-d HH:mm:ss", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd") : string.Empty, // 维修完成时间
                            book.PackagingTime ?? string.Empty,             // 包装时间
                            book.ApplyTime ?? string.Empty,
                            book.ApplyRepairTime ?? string.Empty,
                            book.Datex != null ? book.Datex.Substring(6, 4) + "/" + book.Datex[..2] + "/" + book.Datex.Substring(3, 2) : string.Empty,
                            book.Delivery_nameOut ?? string.Empty,          // 发货快递名称
                            book.Delivery_numberOut ?? string.Empty,
                            book.Notes ?? string.Empty);                    // 发货快递号

                        csvContent.AppendLine(csvLine);
                    }

                    string exportFolderPath = "C:\\WebSite\\XinjeMesApi\\wwwroot\\xlsx";
                    string ambin = "查询数据表" + DateTime.Now.ToString("mm-ss") + ".csv";
                    string csvFilePath = Path.Combine(exportFolderPath, ambin);
                    System.IO.File.WriteAllText(csvFilePath, csvContent.ToString(), Encoding.UTF8);
                    string downloadLink = "/xlsx/" + ambin;  // 下载链接
                    this.response.SetSuccess(downloadLink);
                }
            }

            return this.response;
        }

        /// <summary>
        /// 工程师 .
        /// </summary>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/Obtained")]
        [HttpGet]
        public ResponseModel Obtained()
        {
            List<MesUserRole12> mesUserRole1 = new();
            using (FactoryMesContext factoryMes = new())
            {
                mesUserRole1 = factoryMes.MesUserRole12.FromSqlRaw("select a.GroupType, a.UserName, a.ID  from MesUserRole a  where  a.GroupType='3' or a.GroupType='4' or a.GroupType='5'").ToList();
            }

            this.response.SetData(mesUserRole1);
            return this.response;
        }

        /// <summary>
        /// sldakf.
        /// </summary>
        /// <param name="id">id.</param>
        /// <param name="unknown">unknown.</param>
        /// <returns>.</returns>
        [Route("api/v1/reportForms/DataExport")]
        [HttpGet]
        public ResponseModel DataExport(string id, string? unknown)
        {
            _ = new List<Verifyexport>(); // 核对导出表

            // StringBuilder csvContent = new StringBuilder();
            StringBuilder csvContent = new();
            if (!string.IsNullOrEmpty(id))
            {
                using FactoryMesContext context = new();
                string sQL = string.Empty;
                if (unknown == "不明")
                {
                    sQL = string.Format(
                    "select m.WarehousingDate, m.Delivery_NameIn, m.Delivery_NumberIn, m.Name, m.Contact_Information, m.Product_Model,m.One_Dimensional_Code,m.Product_Category,m.Delivery_Time ,m.Salesman ,m.First_Address from  MainsortRecord m  where m.State= '2' and  m.Contact_Information= '{0}'", "不明");   // SQL语句生成  //核对查询不明
                }
                else
                {
                    sQL = string.Format(
                    "select m.WarehousingDate, m.Delivery_NameIn, m.Delivery_NumberIn, m.Name, m.Contact_Information, m.Product_Model,m.One_Dimensional_Code,m.Product_Category,m.Delivery_Time ,m.Salesman ,m.First_Address from  MainsortRecord m  where m.State= '2' and  m.Contact_Information != '{0}'", "不明");   // SQL语句生成  //核对查询 非不明
                }

                List<Verifyexport> verifyexport = context.Verifyexport.FromSqlRaw(sQL).ToList();
                csvContent.AppendLine("收货时间,快递名称,快递单号,客户名称,产品组别,客户电话,产品型号,产品序列号,首次出库日期,首次出库地址");  // 核对导出表 表头

                foreach (var book in verifyexport)
                {
                    // 字段
                    string csvLine = string.Format(
                        "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}",
                        book.WarehousingDate,
                        book.Delivery_NameIn,
                        book.Delivery_NumberIn,
                        book.Name,
                        book.Product_Category,
                        book.Contact_Information,
                        book.Product_Model,
                        book.One_Dimensional_Code,
                        book.Delivery_Time,
                        book.First_Address);

                    csvContent.AppendLine(csvLine);
                }

                string exportFolderPath = "C:\\WebSite\\XinjeMesApi\\wwwroot\\xlsx";
                string ambin = "分拣数据表" + DateTime.Now.ToString("mm-ss") + "(含维修记录).csv";
                string csvFilePath = Path.Combine(exportFolderPath, ambin);
                System.IO.File.WriteAllText(csvFilePath, csvContent.ToString(), Encoding.UTF8);
                string downloadLink = "/xlsx/" + ambin;  // 下载链接
                this.response.SetSuccess(downloadLink);
            }

            return this.response;
        }
    }
}
